package com.ruoyi.system.util;

import com.alibaba.fastjson2.JSON;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class RequestUtil {
    private static final String HEADER_CONTENT_JSON = "application/json";

    private static final String DEFAULT_CHARSET = "UTF-8";

    private static PoolingHttpClientConnectionManager cm;

    private static CloseableHttpClient httpClient;

    static {
        cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(500);
        cm.setDefaultMaxPerRoute(50);

        RequestConfig globalConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(10000)         // 连接池获取连接超时
                .setConnectTimeout(10000)                   // 连接建立超时
                .setSocketTimeout(30000)                    // 等待响应超时
                .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
                .build();

        httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(globalConfig).build();
    }

    private static CloseableHttpClient getHttpClient() {
        return httpClient;
    }

    public static String doGet(String requestUrl) throws IOException {
        CloseableHttpClient httpClient = getHttpClient();
        HttpGet get = new HttpGet(requestUrl);
        String responseString = httpClient.execute(get, response -> EntityUtils.toString(response.getEntity()));
        get.releaseConnection();
        return responseString;
    }

    public static String doPost(String requestUrl, Object params) throws IOException {
        CloseableHttpClient httpClient = getHttpClient();
        HttpPost post = new HttpPost(requestUrl);
        String paramsStr = JSON.toJSONString(params);
        assert paramsStr != null;
        StringEntity stringEntity = new StringEntity(paramsStr, ContentType.APPLICATION_JSON);
        post.setEntity(stringEntity);
        String responseString = httpClient.execute(post, response -> EntityUtils.toString(response.getEntity()));
        post.releaseConnection();
        return responseString;
    }
}
